/**
 * 表格js操作类
 *
 *
 *
 *
 */





var listTable		= new Object;
listTable.query		= "query";
listTable.filter	= false;
listTable.url		= location.href.lastIndexOf("?") == -1 ? location.href.substring((location.href.lastIndexOf("/")) + 1) : location.href.substring((location.href.lastIndexOf("/")) + 1, location.href.lastIndexOf("?"));
listTable.url		+= "?ajax=1";
listTable.submit_args = '';



/**
 * +-----------------------------------+
 * 获取当前url的参数
 *
 */

/*var URLParams={};
(function(){var A=document.location.search.substr(1).split('&');for (var i=0;i<A.length;i++){var B=A[i].split('=');var C=decodeURIComponent(B[0]);var D=decodeURIComponent(B[1]);URLParams[C]=D;}})();
*/
/**
 * +-----------------------------------+
 */

/**
 * +-----------------------------------+
 * 获取当前url的参数
 *
 */
var URLParams={};
(function(){var A=document.location.search.substr(1).split('&');for(var i=0;i<A.length;i++){var B=A[i].split('=');var C=decodeURIComponent(B[0]);var D=decodeURIComponent(B[1]);URLParams[C]=D;}
var L=document.location;
URLParams['fileurl']=L['protocol']+'//'+L['hostname']+L['port']+L['pathname'];
})();
/**
 * +-----------------------------------+
 */






/**
 * 创建一个可编辑区，一般用于编辑列表中的标题或其他经常修改的内容
 * 
 * 
 */
listTable.edit = function(obj, act, id) {
	var tag = obj.firstChild.tagName;
	if (typeof(tag) != "undefined" && tag.toLowerCase() == "input") {
		return;
	}

	/* 保存原始的内容 */
	var org = obj.innerHTML;
	var val = is_ie ? obj.innerText : obj.textContent;

	/* 创建一个输入框 */
	var txt = document.createElement("INPUT");
	txt.value = (val == 'N/A') ? '' : val;
	txt.className = 'text';
	txt.style.width = (obj.offsetWidth + 20) + "px" ;

	/* 隐藏对象中的内容，并将输入框加入到对象中 */
	obj.innerHTML = "";
	obj.appendChild(txt);
	txt.focus();

	/* 编辑区输入事件处理函数 */
	txt.onkeypress = function(e) {
		var evt = fixEvent(e);
		var obj = get_srcElement(e);

		if (evt.keyCode == 13) {
			obj.blur();
			return false;
		}

		if (evt.keyCode == 27) {
			obj.parentNode.innerHTML = org;
		}
	}



	/* 编辑区失去焦点的处理函数 */
	txt.onblur = function(e) {


		var thetxt = trim(txt.value);

		if (org != thetxt && thetxt != '') {
			
			// 内容有变化，并且不为空
			var mod = URLParams['mod'];

			if(mod=='') mod = 'content';
			

			// 如果是分类咋办
			var isclass = '';
			olist = document.getElementById("listDiv");
			if(olist.alt=='treelist') {
				isclass = '&isclass=1';
			}
			var action = 'editf';
			if(olist.alt=='special') {
				action = 's.editf';
			} else if (olist.alt == 'speciallist')
			{	
				action = 's.ceditf';
			} else if (olist.alt == 'siteart')
            {
                action  = 'ca.editf';
            }

listTable.url = listTable.url + '&mod='+mod+'&action='+action+isclass+"&act="+act+"&val=" + encodeURIComponent(thetxt) + "&id=" +id;
			 //alert(listTable.url);
			res = Ajax.call(listTable.url, "&act="+act+"&val=" + encodeURIComponent(thetxt) + "&id=" +id, null, "POST", "JSON", false);
//alert(listTable.url);
//location.href=listTable.url;

			if (res.message) {
				alert(res.message);
			}

			if(res.id && (res.act == 'goods_auto' || res.act == 'article_auto')) {
				document.getElementById('del'+res.id).innerHTML = "<a href=\""+ thisfile +"?goods_id="+ res.id +"&act=del\" onclick=\"return confirm('"+deleteck+"');\">"+deleteid+"</a>";
			}
			obj.innerHTML = (res.error == 0) ? res.content : org;
		} else {
			obj.innerHTML = org;
		}
	}
}

function checkinfos(){
    if (request.readyState == 4)
        if (request.status == 200){
            text    = request.responseText;
            alert(text);
        } else if (request.status == 404)
            alert("Request URL does not exist");
        else
            alert("Error: status code is " + request.status);
}



/**
 * 切换状态，一般用于更改某个标志的状态
 *admin.php?ajax=1&&mod=members&action=toggle&f=display&val=1&cval=0&id=20
 *
 */
listTable.toggle = function(obj, f, val, id, toggle_action) {
	var cval = parseInt(obj.innerHTML);

	var toggle_action = typeof(toggle_action) == 'undefined' ? 'toggle' : toggle_action;

	var mod = URLParams['mod'];
	if(mod=='') mod = 'content';
	


	args = '&mod='+mod+
			'&action='+ toggle_action +
			'&f='+f+
			'&val='+val+
			'&cval='+cval+
			'&id='+id
			;



//	location.href=this.url + '&' + args;
//	alert(this.url + '&' + args);
	var res = Ajax.call(this.url, args, null, "GET", "JSON", false);
	
	if (res.message) {
		alert(res.message+"fdsfds");
	}

	if (res.error == 0) {
		obj.innerHTML = res.content;
		if(parseInt(res.content) == 0) {
			obj.className = 'btn_no';
		} else {
			obj.className = 'btn_yes';
		}
	}

}




/**
 * 获取filter中的参数
 * 除了
 *
 */
listTable.getArgs = function() {
	var args = '';
	var except = new Array();

	if(!listTable.filter) {
		listTable.filter = URLParams;
	}


	for(var i=0;i<this.getArgs.arguments.length;i++) { 
		except[i] = this.getArgs.arguments[i];
	}


	var find = false;
	for(var i in listTable.filter) {
		if(typeof(listTable.filter[i]) != "function") {

			if(i=='fileurl') continue;

			find = false;
			for(var j=0;j<except.length;j++) {
				if(except[j] == i) {
					find = true;
					break;
				}
			}

			if(find == false) {
				args += "&" + i + "=" + listTable.filter[i];
			}
		}
	}
	return args;
}
/*包含*/
listTable.getArgsi = function() {
	var args = '';
	var except = new Array();

	if(!listTable.filter) {
		listTable.filter = URLParams;
	}


	for(var i=0;i<this.getArgsi.arguments.length;i++) {
		except[i] = this.getArgsi.arguments[i];
	}


	var find = false;
	for(var i in listTable.filter) {
		if(typeof(listTable.filter[i]) != "function") {

			find = false;
			for(var j=0;j<except.length;j++) {
				if(except[j] == i) {
					find = true;
					break;
				}
			}

			if(find == true) {
				args += "&" + i + "=" + listTable.filter[i];
			}
		}
	}
	return args;
}



/**
 * 切换排序方式，点击表头，按照表头切换顺序
 *
 *
 */
listTable.sort = function(sort_by, sort_order, oldflag) {
	// 从当前url参数中获取除了 orderby 和 desc 以外的参数
	
	var args = '';
	args = this.getArgs('orderby','desc', 'oldflag');
	args += '&orderby=' + sort_by + '&desc='+sort_order;
	if(oldflag) args += '&oldflag=' + oldflag;


	//location.href=this.url + args;
	//alert(this.url + args);
	// 分页大小
	// this.filter['page_size'] = this.getPageSize();
	Ajax.call(this.url, args, this.listCallback, "GET", "JSON");
}



/**
 * 列表翻页
 *
 */
listTable.gotoPage = function(page) {
	var args = '';
	args = this.getArgs('page');
	if (page != null) args += '&page=' + page;
	this.loadList(args);
}

/**
 * 载入列表
 */
listTable.loadList = function(args) {
	Ajax.call(this.url, args, this.listCallback, "GET", "JSON");
}

listTable.delHandler = function(tp) {
	if(tp=='ok'){
		// 点击了确认按钮，
		//location.href=listTable.url +  listTable.submit_args;
		//alert(args);
		// alert(listTable.url);
		Ajax.call(listTable.url, listTable.submit_args, listTable.listCallback, "GET", "JSON");
	}
	if(tp=='cancel'){}
	if(tp=='close'){}
	listTable.submit_url='';
}


/**
 * 删除一条记录
 *
 */
listTable.del = function(id) {
	args = listTable.getArgs('action','id');


	var action = URLParams['action'];
	var del_action = action.substr(0, action.lastIndexOf('.')+1) + 'del';
	args = args + '&action='+del_action+'&id='+id;
	listTable.submit_args = args;

	// alert(listTable.submit_args);


	ymPrompt.confirmInfo(
		{
			msgCls:'confirm',
			message:'<br />您是否要删除本条记录？删除后将无法恢复！<br />点击“确认”按钮继续删除，“取消”按钮取消操作。',
			title:'确认消息',
			height:180,
			width:300,
			handler:listTable.delHandler}
	);
	return false;
}



listTable.getCheckId = function() {
	var cont = document.getElementById("listDiv").getElementsByTagName('INPUT');

	var id = '';
	
	for(var i=0;i<cont.length;i++) {
		if(cont[i].type == "checkbox" &&
			cont[i].name=='id[]' &&
			cont[i].checked &&
			(thisid=parseInt(cont[i].value))
		) {
			if(!isNaN(thisid)) id += ','+thisid;
		}
	}
	if(id != '') id = id.substr(1);


	return id;
}


/**
 * 列表操作
 * check/uncheck
 * setflag/unsetflag
 * del
 * move
 * copy
 * reorder
 */
listTable.liop = function(action) {
	var optarget = $('optarget');

	if('checkbatch'==action || 'uncheckbatch'==action) {
		optarget.innerHTML = '';
	} else if('setflag'==action || 'unsetflag'==action) {
		optarget.innerHTML = $('selflag').innerHTML;
	} else if('del'==action) {
		optarget.innerHTML = '';
	} else if('move'==action) {
		optarget.innerHTML = $('selclass').innerHTML;
	} else if('copy'==action) {
		optarget.innerHTML = $('selclass').innerHTML;
	} else if('reorder'==action) {
		optarget.innerHTML = '';
	}
}


listTable.submitop = function() {
	var id = listTable.getCheckId();

	if(id == '') {
		ymPrompt.alert({message:'您未选择任何记录，无法继续操作！',slideShowHide:false,title:'错误！',handler:null});
	} else {

		args = listTable.getArgs('action','id','flagvalue','cidvalue');
		action = $('oplist').value;
		args +='&action='+action;

		

		if('checkbatch'==action || 'uncheckbatch'==action) {
			args += '&id='+id;
		} else if('setflag'==action || 'unsetflag'==action) {
			var flagvalue = parseInt($('opflag').value);
			if(isNaN(flagvalue)) {
				return false;
			}
			args += '&id='+id+'&flagvalue='+flagvalue;
		} else if('del'==action) {
			ymPrompt.confirmInfo(
					{
						msgCls:'confirm',
						message:'<br />您是否要删除选定的记录？删除后将无法恢复！<br />点击“确认”按钮继续删除，“取消”按钮取消操作。',
						title:'确认消息',
						height:180,
						width:300,
						handler:listTable.delHandler}
				);

			args += '&id='+id;
			listTable.submit_args = args;
			var handler_submit = 1;
		} else if('move'==action) {
			var cidvalue = parseInt($('opcid').value);
			if(isNaN(cidvalue)) {
				return false;
			}
			args += '&id='+id+'&cidvalue='+cidvalue;
		} else if('copy'==action) {
			var cidvalue = parseInt($('opcid').value);
			if(isNaN(cidvalue)) {
				return false;
			}
			args += '&id='+id+'&cidvalue='+cidvalue;
		} else if('reorder'==action) {
			optarget.innerHTML = '';
		}
		// alert(args);
		if(handler_submit){} else {
			Ajax.call(this.url, args, this.listCallback, "GET", "JSON");
		}
	}
}







/**
 * +-------------------------------------------------------+
 * 列表翻页相关函数定义
 * +-------------------------------------------------------+
 */


listTable.changePageSize = function(e) {
	var evt = Utils.fixEvent(e);
	if (evt.keyCode == 13) {
		listTable.gotoPage();
		return false;
	};
}

listTable.getPageSize = function() {
	var ps = 15;

	page_size = document.getElementById("page_size");

	if (page_size) {
		ps = isInt(page_size.value) ? page_size.value : 15;
		setcookie('HOTADMINS[psize]', ps, 1000);
	}
}
/**
 * +-----------------------------------------------------------------+
 */




/**
 * 向列表块中写入列表内容
 *
 *
 */
listTable.listCallback = function(result, txt) {
	if (result.error > 0) {
		alert(result.message);
	} else {


		





		try {

			// document.getElementById('rrrrrr').value = result.content;

			document.getElementById('listDiv').innerHTML = result.content;

			if(result.message != '') {
				ymPrompt.alert({message:result.message,slideShowHide:false,title:'操作成功！',handler:null});
			}


			/*
			if (typeof result.filter == "object") {
				listTable.filter = result.filter;
			}
			
			listTable.pageCount = result.page_count;
			*/
		}catch (e) {
			alert(e.message);
		}
	}
}







/**
 * 列表全选
 *
 *
 */
listTable.selectAll = function(obj, chk) {
	this.checkbox(obj, chk, 'a');
}

listTable.selectReverse = function(obj, chk) {
	this.checkbox(obj, chk, 'r');
}

listTable.checkbox = function(obj, chk, checked) {
	if (obj == null) {
		obj = document.getElementById("listDiv");
	}
	if (chk == null) {
		chk = 'id';
	}
	checked = (checked == null || checked == 'a') ? 'a' : 'r';

	var elems = obj.getElementsByTagName("INPUT");

	for (var i=0; i < elems.length; i++) {
		if (elems[i].name == chk || elems[i].name == chk + "[]") {
			elems[i].checked = (checked == 'a') ? true : !elems[i].checked;
		}
	}
}















listTable.addRow = function(checkFunc) {
  cleanWhitespace(document.getElementById("listDiv"));
  var table = document.getElementById("listDiv").childNodes[0];
  var firstRow = table.rows[0];
  var newRow = table.insertRow(-1);
  newRow.align = "center";
  var items = new Object();
  for(var i=0; i < firstRow.cells.length;i++) {
    var cel = firstRow.cells[i];
    var celName = cel.getAttribute("name");
    var newCel = newRow.insertCell(-1);
    if (!cel.getAttribute("ReadOnly") && cel.getAttribute("Type")=="TextBox")
    {
      items[celName] = document.createElement("input");
      items[celName].type  = "text";
      items[celName].style.width = "50px";
      items[celName].onkeypress = function(e)
      {
        var evt = Utils.fixEvent(e);
        var obj = get_srcElement(e);

        if (evt.keyCode == 13)
        {
          listTable.saveFunc();
        }
      }
      newCel.appendChild(items[celName]);
    }
    if (cel.getAttribute("Type") == "Button")
    {
      var saveBtn   = document.createElement("input");
      saveBtn.type  = "image";
      saveBtn.src = "./images/icon_add.gif";
      saveBtn.value = save;
      newCel.appendChild(saveBtn);
      this.saveFunc = function()
      {
        if (checkFunc)
        {
          if (!checkFunc(items))
          {
            return false;
          }
        }
        var str = "act=add";
        for(var key in items)
        {
          if (typeof(items[key]) != "function")
          {
            str += "&" + key + "=" + items[key].value;
          }
        }
        res = Ajax.call(listTable.url, str, null, "POST", "JSON", false);
        if (res.error)
        {
          alert(res.message);
          table.deleteRow(table.rows.length-1);
          items = null;
        }
        else
        {
          document.getElementById("listDiv").innerHTML = res.content;
          if (document.getElementById("listDiv").childNodes[0].rows.length < 6)
          {
             listTable.addRow(checkFunc);
          }
          items = null;
        }
      }
      saveBtn.onclick = this.saveFunc;

      //var delBtn   = document.createElement("input");
      //delBtn.type  = "image";
      //delBtn.src = "./images/no.gif";
      //delBtn.value = cancel;
      //newCel.appendChild(delBtn);
    }
  }

}



get_srcElement = function(e) {
	if (typeof e == "undefined") e = window.event;
	var src = document.all ? e.srcElement : e.target;
	return src;
}

function list_onload() {
	var list = document.getElementById("listDiv");
	if (list) {


		/* 鼠标移进移出暂存变量 */
		var oldclassName = '';


		/* 给列表的一行绑定鼠标上事件 */
		list.onmouseover = function(e) {
			obj = get_srcElement(e);



			if (obj) {
				if(list.alt=='treelist') {
					while(1) {
						if(	// tbody
							obj.parentNode.parentNode.tagName.toLowerCase() == "table" &&
							obj.parentNode.parentNode.className=='treeNode' &&
							obj.tagName.toLowerCase() == "tr"
							||
							obj.parentNode.tagName.toLowerCase() == "table" && 
							obj.parentNode.className=='treeNode' &&
							obj.tagName.toLowerCase() == "tr"
						
						) {
							// alert(obj.tagName);
							row = obj;
							break;
						} else if(obj.parentNode.tagName.toLowerCase() == "body") {
							return false;
							break;
						}
						obj = obj.parentNode;
					}
				} else {
					if (obj.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode;
					else if (obj.parentNode.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode.parentNode;
					else return;
				}


				

				oldclassName = row.className
				row.className += ' tr_hover';
				// alert(row.className);
			}
		}

		/* 给列表的一行绑定鼠标出事件 */
		list.onmouseout = function(e) {
			obj = get_srcElement(e);

			if (obj) {
				if (obj.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode;
				else if (obj.parentNode.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode.parentNode;
				else return;

				row.className=oldclassName;

			}
		}


		/* 给列表全选按钮绑定onclick事件 */
		

		/* 给列表反选按钮绑定onclick事件 */


		



		/* 给列表反选按钮绑定onclick事件 */
		list.onclick = function(e) {
			var obj = get_srcElement(e);

			if (obj.tagName == "INPUT" && obj.type == "checkbox") {
				if (!document.forms['listForm']) {
					return;
				}


				var nodes = document.forms['listForm'].elements;
				var checked = false;

				for (i = 0; i < nodes.length; i++) {
					if (nodes[i].checked) {
						checked = true;
						break;
					}
				}



				if(document.getElementById("btnSubmit")) {
					document.getElementById("btnSubmit").disabled = !checked;
				}

				for (i = 1; i <= 10; i++) {
					if (document.getElementById("btnSubmit" + i)) {
						document.getElementById("btnSubmit" + i).disabled = !checked;
					}
				}
			}
		}
	}
}






